//
//  PersonalUserAlbumViewController.m
//  ChatForHot
//
//  Created by wr on 2018/10/11.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "PersonalUserAlbumViewController.h"
#import "PreviewUserPhotoViewController.h"
#import "UserPhotoUploadViewController.h"
#import "PersonalUserPhotoCell.h"
#import "HCAssetModel.h"

@interface PersonalUserAlbumViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,MWPhotoBrowserDelegate,UploadPhotoSelectedDelegate>

@property (nonatomic, assign) PhotoType photoType;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UICollectionView *HOTCHATalbumCollectionView;
@property (nonatomic, strong) UIButton *HOTCHATuploadBar;
@property (nonatomic, strong) NSMutableArray *uploadArray;
@property (nonatomic, assign) NSInteger selectedRow;
@property (nonatomic, strong) PreviewUserPhotoViewController *HOTCHATphotoBrowser;
@property (nonatomic, strong) UINavigationController *nv;
@property (nonatomic, strong) UIButton *HOTCHATupBtn;
@property (nonatomic, strong) UIButton *HOTCHATdelButton;
@property (nonatomic, strong) UIButton *HOTCHATdelButton2;
@property (nonatomic, assign) BOOL isEditMode;
@property (nonatomic, assign) BOOL isUploading;
@property (nonatomic, assign) BOOL loadself;
@end

@implementation PersonalUserAlbumViewController

- (instancetype)initWithPhotoType:(NSInteger)photoType {
    if (self = [super init]) {
        self.photoType = photoType;
        [self HOTCHATstartLoading];
        [self HOTCHATgetPhotos];
    }
    return self;
}

- (void)HOTCHATdidInitialized {
    [super HOTCHATdidInitialized];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.HOTCHATphotoBrowser = [[PreviewUserPhotoViewController alloc] initWithDelegate:self];
    self.HOTCHATphotoBrowser.displayActionButton = NO;
    self.HOTCHATphotoBrowser.displayNavArrows = YES;
    self.HOTCHATphotoBrowser.displaySelectionButtons = NO;
    self.HOTCHATphotoBrowser.alwaysShowControls = NO;
    self.HOTCHATphotoBrowser.zoomPhotosToFill = YES;
    self.HOTCHATphotoBrowser.enableGrid = NO;
    self.HOTCHATphotoBrowser.startOnGrid = NO;
    self.HOTCHATphotoBrowser.isSelf = YES;
    [self.HOTCHATphotoBrowser setCurrentPhotoIndex:0];
    
    self.nv = [[UINavigationController alloc] initWithRootViewController:self.HOTCHATphotoBrowser];
    
    self.dataArray = [[NSMutableArray alloc] init];
    self.uploadArray = [[NSMutableArray alloc] init];
}

- (void)HOTCHATInsertSubViews {
    [super HOTCHATInsertSubViews];
    self.selectedRow = -1;
    @weakify(self)
    self.HOTCHATupBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.HOTCHATupBtn setBackgroundImage:[[UIImage imageNamed:@"personal_iden_sav_n"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 15, 15, 15) resizingMode:(UIImageResizingModeStretch)] forState:UIControlStateNormal];
    [self.HOTCHATupBtn setBackgroundImage:[[UIImage imageNamed:@"personal_iden_sav_h"]resizableImageWithCapInsets:UIEdgeInsetsMake(15, 15, 15, 15) resizingMode:(UIImageResizingModeStretch)] forState:UIControlStateHighlighted];
    [self.HOTCHATupBtn setTitle:NSLocalizedString(@"userPhoto1", nil) forState:UIControlStateNormal];
    [self.HOTCHATupBtn setTitle:NSLocalizedString(@"userPhoto1", nil) forState:UIControlStateHighlighted];
    [self.view addSubview:self.HOTCHATupBtn];
    [[self.HOTCHATupBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self)
        [self HOTCHATuploadPhoto];
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    self.HOTCHATalbumCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.HOTCHATalbumCollectionView.dataSource = self;
    self.HOTCHATalbumCollectionView.delegate = self;
    [self.HOTCHATalbumCollectionView registerClass:[PersonalUserPhotoCell class] forCellWithReuseIdentifier:@"PersonalUserPhotoCell"];
    self.HOTCHATalbumCollectionView.showsHorizontalScrollIndicator = NO;
    self.HOTCHATalbumCollectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.HOTCHATalbumCollectionView];
    
    self.HOTCHATdelButton = [[UIButton alloc] init];
    self.HOTCHATdelButton.titleLabel.font = [UIFont systemFontOfSize:16];
    
    [self.HOTCHATdelButton setTitle:NSLocalizedString(@"userPhoto2", nil) forState:(UIControlStateNormal)];
    [self.HOTCHATdelButton addTarget:self action:@selector(HOTCHATDeletePhotoAction) forControlEvents:(UIControlEventTouchUpInside)];
    UIColor *color = [UIColor colorFromHexString:@"#F04D32"];
    [self.HOTCHATdelButton setTitleColor:color forState:UIControlStateNormal];
    [self.HOTCHATdelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [self.HOTCHATdelButton setBackgroundImage:[[UIImage imageNamed:@"personal_btn_del"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)] forState:(UIControlStateNormal)];
    [self.HOTCHATdelButton setBackgroundImage:[[UIImage imageNamed:@"personal_btn_del_hig"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)] forState:(UIControlStateHighlighted)];
    [self.view addSubview:self.HOTCHATdelButton];
    
    self.HOTCHATdelButton2 = [[UIButton alloc] init];
    self.HOTCHATdelButton2.titleLabel.font = [UIFont systemFontOfSize:16];
    
    [self.HOTCHATdelButton2 setTitle:NSLocalizedString(@"userPhoto2", nil) forState:(UIControlStateNormal)];
    [self.HOTCHATdelButton2 addTarget:self action:@selector(HOTCHATDeletePhotoAction2) forControlEvents:(UIControlEventTouchUpInside)];
    [self.HOTCHATdelButton2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.HOTCHATdelButton2 setTitleColor:color forState:UIControlStateHighlighted];
    self.HOTCHATdelButton2.hidden = YES;
    
    [self.HOTCHATdelButton2 setBackgroundImage:[[UIImage imageNamed:@"personal_btn_del_hig"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)] forState:(UIControlStateNormal)];
    [_HOTCHATdelButton2 setBackgroundImage:[[UIImage imageNamed:@"personal_btn_del"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)] forState:(UIControlStateHighlighted)];
    [self.view addSubview:self.HOTCHATdelButton2];
    
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.HOTCHATalbumCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.bottom.equalTo(self.HOTCHATupBtn.mas_top).offset(-10);
    }];
    [self.HOTCHATupBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 55);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-84);
        make.height.mas_equalTo(44);
    }];
    [self.HOTCHATdelButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.HOTCHATupBtn);
        make.bottom.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(kScreenWidth - 55);
    }];
    [self.HOTCHATdelButton2 mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.HOTCHATdelButton);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark UICollectionDatasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PersonalUserPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PersonalUserPhotoCell" forIndexPath:indexPath];
    cell.model = [self.dataArray objectAtIndex:indexPath.row];
    cell.isEditMode = self.isEditMode;
    return cell;
}

#pragma mark UICollectionview Delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isEditMode) {
        PersonalUserPhotoCell *cell = (PersonalUserPhotoCell *)[collectionView cellForItemAtIndexPath:indexPath];
        cell.model.isSelected = !cell.model.isSelected;
    }else{
        [self HOTCHATpreviewPhotoWithIndex:indexPath.row];
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger cellwidth = (CGRectGetWidth(collectionView.frame) - 10 * 4) / 3;
    return CGSizeMake(cellwidth, cellwidth);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

#pragma mark - Actions

- (void)HOTCHATDeletePhotoAction{
    self.isEditMode = YES;
    self.HOTCHATdelButton.hidden = YES;
    self.HOTCHATdelButton2.hidden = NO;
    [self.HOTCHATalbumCollectionView reloadData];
}
- (void)HOTCHATDeletePhotoAction2{
    self.isEditMode = NO;
    self.HOTCHATdelButton.hidden = NO;
    self.HOTCHATdelButton2.hidden = YES;
    [self HOTCHATdeleteVideos];
    [self.HOTCHATalbumCollectionView reloadData];
}
- (void)sendPhoto{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)HOTCHATuploadPhoto{
    UserPhotoUploadViewController *pvc = [[UserPhotoUploadViewController alloc] init];
    pvc.maxCount = 20 - self.dataArray.count;
    pvc.delegate = self;
    [self.navigationController pushViewController:pvc animated:YES];
}
- (void)HOTCHATselectedPhotoArray:(NSArray *)array{
    NSLog(@"%@_pp_",[NSThread currentThread]);
    if (array.count > 0) {
        self.loadself = YES;
        [self.uploadArray addObjectsFromArray:array];
    }
    for (id obj in self.uploadArray) {
        if ([obj isKindOfClass:[HCAssetModel class]]) {
            HCAssetModel *model = obj;
            if (model.isUping) {
                break;
            }else if(model.uploadSuccess){
                continue;
            }else{
                [self HOTCHATuploadPhotoWithObj:obj];
                break;
            }
        }else if ([obj isKindOfClass:[UIImage class]]){
            [self HOTCHATuploadPhotoWithObj:obj];
        }
    }
    [self HOTCHATstartLoading];
    [self HOTCHATstartUpload];
}

- (void)HOTCHATstartUpload {
    if (self.isUploading) {
        return;
    }
    if (self.uploadArray.count > 0) {
        [self HOTCHATuploadPhotoWithObj:[self.uploadArray firstObject]];
    }else{
        if (self.loadself) {
            [self HOTCHATgetPhotos];
        }else{
            [self HOTCHATstopLoading];
        }
    }
}

- (void)HOTCHATuploadPhotoWithObj:(id)obj{
    @weakify(self)
    
    NSData *imgData;
    if ([obj isKindOfClass:[UIImage class]]) {
        imgData = [obj HOTCHATcompressQualityData];
    }else if ([obj isKindOfClass:[HCAssetModel class]]){
        HCAssetModel *model = obj;
        imgData = [self fetchDataFromAsset:model.asset];
        UIImage *newimg = [UIImage imageWithData:imgData];
        if (newimg) {
            imgData = [newimg HOTCHATcompressQualityData];
        }
    }else{
        [self HOTCHATstopLoading];
        return;
    }
    if (imgData.length > 0) {
        @strongify(self)
        self.isUploading = YES;
        NSMutableDictionary *mparameters = [[NSMutableDictionary alloc] init];
        [mparameters setValue:[APPINFO defaultManager].accountid forKey:@"accountid"];
        [mparameters setValue:[NSNumber numberWithInteger:self.photoType] forKey:@"type"];
        [NetWorkTool HOTCHATUploadImageData:UerPhotoUploadPic_URL parameters:mparameters fileData:^(id<AFMultipartFormData>  _Nonnull formData) {
            [formData appendPartWithFileData:imgData name:@"uploadfile" fileName:@"headpic.jpg" mimeType:@"image/jpeg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull HOTCHATtask, NSString * _Nonnull HOTCHATmsgCode, NSDictionary * _Nonnull HOTCHATresultDic) {
            @strongify(self)
            self.isUploading = NO;
            
            if ([HOTCHATmsgCode isEqualToString:@"0"]) {
                [NetWorkTool HOTCHATUpdateToken];
                [self HOTCHATgetPhotos];
                [self HOTCHATupNextPhoto];
            }else{
                [self HOTCHATstopLoading];
            }
            
            if ([HOTCHATmsgCode isEqualToString:@"1"]) {
                NSString *message = [HOTCHATresultDic valueForKey:@"message"];
                if (message.length > 0) {
                    [NetWorkTool HOTCHATshowMessage:message];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nonnull HOTCHATtask, NSError * _Nonnull error) {
            @strongify(self)
            self.isUploading = NO;
            [self HOTCHATstopLoading];
        }];
        
    }else{
        [self HOTCHATupNextPhoto];
    }
    
}

- (void)HOTCHATupNextPhoto{
    if (self.uploadArray.count > 0) {
        [self.uploadArray removeObjectAtIndex:0];
    }
    [self HOTCHATstartUpload];
}

- (NSData *)fetchDataFromAsset:(PHAsset *)asset {
    __block NSData *tmpData = [NSData data];
    if (asset.mediaType == PHAssetMediaTypeImage) {
        PHImageRequestOptions *request = [PHImageRequestOptions new];
        request.version = PHImageRequestOptionsVersionCurrent;
        request.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
        request.resizeMode = PHImageRequestOptionsResizeModeNone;
        request.synchronous = YES;
        [[PHImageManager defaultManager] requestImageDataForAsset:asset
                                                          options:request
                                                    resultHandler:
         ^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
             tmpData = [NSData dataWithData:imageData];
         }];
    }
    return tmpData;
}

#pragma mark - getUserPhoto

- (void)HOTCHATgetPhotos{
    @weakify(self)
    NSMutableDictionary *mparameters = [[NSMutableDictionary alloc] init];
    [mparameters setValue:[APPINFO defaultManager].accountid forKey:@"accountid"];
    [mparameters setValue:[NSNumber numberWithInteger:self.photoType] forKey:@"type"];
    [NetWorkTool HOTCHATRequestWithStringURL:GetUerPhotoPic_URL progress:^(NSProgress * _Nonnull progress) {
        
    } RequestWay:@"GET" Parma:mparameters SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
        @strongify(self)
        if (self.uploadArray.count == 0) {
            [self HOTCHATstopLoading];
        }
        if(isSucess){
            NSArray *keyDic = [resultDictionary valueForKey:@"data"];
            if (keyDic.count > 0) {
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:[PersonalUserPhotoModel HOTCHATgetArrayFromDic:resultDictionary]];
                [self.HOTCHATalbumCollectionView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
                [self.HOTCHATalbumCollectionView hideEmptyView];
            }else {
                [self.HOTCHATalbumCollectionView showEmptyViewWithImage:[UIImage imageNamed:@"p_album_ic_no"]];
            }
            
        }
    } FailureBlock:^(NSError * _Nonnull error) {
        @strongify(self)
        [self HOTCHATstopLoading];
    }];
}

#pragma mark - Preview
- (void)HOTCHATpreviewPhotoWithIndex:(NSInteger)index{
    [self.HOTCHATphotoBrowser reloadData];
    [self.HOTCHATphotoBrowser setCurrentPhotoIndex:index];
    [self presentViewController:self.nv animated:YES completion:^{
    }];
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser{
    return self.dataArray.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index{
    PersonalUserPhotoModel *model = [self.dataArray objectAtIndex:index];
    return [MWPhoto photoWithURL:[NSURL URLWithString:[model.picAddress HOTCHATTotalStringUrl]]];
}

- (void)deletePhotoAtIndex:(NSInteger)index{
    UIAlertController *asheet = [UIAlertController alertControllerWithTitle:nil message:@"Delete the photo?" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancelaction = [UIAlertAction actionWithTitle:NSLocalizedString(@"CANCELBUTTON", nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *okaction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OKBUTTON", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if (index >= 0 && index < self.dataArray.count) {
            PersonalUserPhotoModel *model = [self.dataArray objectAtIndex:index];
            [self HOTCHATdeletePhotoByID:model.photoid];
            [self.dataArray removeObjectAtIndex:index];
            [self.HOTCHATalbumCollectionView reloadData];
            [self.HOTCHATphotoBrowser reloadData];
        }
    }];
    
    [asheet addAction:cancelaction];
    [asheet addAction:okaction];
    
    [self.nv presentViewController:asheet animated:YES completion:^{
    }];
}

- (void)HOTCHATdeletePhotoByID:(NSString *)photoID{
    @weakify(self)
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:photoID forKey:@"photoid"];
    [NetWorkTool HOTCHATRequestWithStringURL:GetUerPhotoDeletePic_URL progress:^(NSProgress * _Nonnull progress) {
    } RequestWay:@"POST" Parma:dic SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
        @strongify(self)
        if (isSucess) {
            [NetWorkTool HOTCHATshowMessage:NSLocalizedString(@"userPhoto6", nil)];
            [NetWorkTool HOTCHATUpdateToken];
            [self HOTCHATgetPhotos];
        }
    } FailureBlock:^(NSError * _Nonnull error) {
    }];
}

- (void)HOTCHATdeleteVideos{
    for (NSInteger i = self.dataArray.count - 1; i >= 0; i --) {
        PersonalUserPhotoModel *model = self.dataArray[i];
        if (model.isSelected) {
            [self HOTCHATdeletePhotoByID:model.photoid];
            [self.dataArray removeObjectAtIndex:i];
        }
    }
}

@end
